package servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.persistence.SpringUtils;

public class FileUpload extends HttpServlet {

	private static File tempDir ;
	private static int fileSizeMaxInMemory;
	private static int fileSizeMax;
	private static final Log LOG = LogFactory.getLog(FileUpload.class);
	private final static String FILE_UPLOADED_SESSION_KEY = "__LNW_FILE_KEY";

	@Override
	public void init() throws ServletException {
		fileSizeMaxInMemory = 4000096;

		String tempDirUploadServlet = null;
		if(tempDirUploadServlet!= null){
			tempDir = new File(tempDirUploadServlet);
		}

		fileSizeMax = 4000096;
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req);
	}

	public boolean processRequest(HttpServletRequest request) {
		try {
			ServletFileUpload upload = createServletFileUpload();
			List<FileItem> files = (List<FileItem>)upload.parseRequest(request);

			// la guardo en disco
			for(FileItem f : files){
				if (!f.isFormField() && f.getFieldName().equals("file")){
					File uploadedFile = new File("C:\\uploaded\\" + f.getName());
				    f.write(uploadedFile);

				    // la guardo en la base
				    // TODO: ESTO QUEDARIA MEJOR SI SE HACE CON UN STORE. HABRIA QUE
				    // CREAR LA CLASE DEL STORE PASANDO LOS PARAMETROS Y HACER EL
				    // INSERT EN LA BASE. ver: sma.server.dao.OficialDao$SpUpdateOficial
				    PreparedStatement pstmt = SpringUtils.getJdbcTemplate().getDataSource().getConnection()
				    		.prepareStatement("INSERT INTO FOTO (Descripcion, Foto) VALUES (?,?)");

					pstmt.setString(1, "La foto clob: " + f.getName());
					FileInputStream in = new FileInputStream(uploadedFile);
					pstmt.setBinaryStream (2, in, (int) uploadedFile.length() );
					pstmt.execute();
				}
			}



			//setFilesToShow(files,request);
		}
		catch(Exception e) {
			LOG.error("Error al subir un archivo", e);
			return false;
		}
		return true;
	}

	private ServletFileUpload createServletFileUpload() {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(fileSizeMaxInMemory);
		if(tempDir != null){
			factory.setRepository(tempDir);
		}
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(fileSizeMax);
		return upload;
	}


	protected static void setFilesToShow(List files, HttpServletRequest request) {
		request.getSession().setAttribute( FILE_UPLOADED_SESSION_KEY, files );
	}

//	public static FileItem getFileUploaded() {
//		List filesUploaded = getFilesUploaded();
//		if(filesUploaded == null)
//			return null;
//		return (FileItem) (filesUploaded.size() > 0 ? filesUploaded.get(0) : null);
//	}
//
//	public static List getFilesUploaded() {
//		List  files = (List) UserContext.getInstance().getRequest().getSession().getAttribute( FILE_UPLOADED_SESSION_KEY );
//		UserContext.getInstance().getRequest().getSession().removeAttribute( FILE_UPLOADED_SESSION_KEY );
//		return files;
//	}

}
